# -*- coding:utf-8 -*-
"""
@project: AutoTesting_pulsar
@author: chenhh
@file: Read_Data.py
@ide: PyCharm
@time: 2021/1/25
"""
import json
import jsonpath
import xlrd
import os
import copy
from Config.Config import Config
from Common.Log import logger

class Readxlsdata(object):

    def __init__(self, flie_name):
        #self.config = Config()
        #excel_path = self.config.casedata_path
        BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        self.excel_file = BASE_PATH + flie_name
        self.book = xlrd.open_workbook(self.excel_file)

    def Table_rows(self):
        table = self.book.sheet_by_index(0)
        return table

    def get_casedata(self):
        """
        :return:
        """
        data_list = []
        title_list = []
        table = self.book.sheet_by_index(0)
        for n in range(1, table.nrows):
            # 每行第4列 是否运行
            #if table.cell_value(n, 4) == '否':
            #   continue
            # 每行第2列， 标题单独拿出来
            title_list.append(table.cell_value(n, 2))

            # 返回该行的所有单元格组成的数据 table.row_values(0) 0代表第1列
            case_model = table.cell_value(n, 0)
            case_number = table.cell_value(n, 1)
            case_title = table.cell_value(n, 2)
            path = table.cell_value(n, 3)
            is_token = table.cell_value(n, 5)
            method = table.cell_value(n, 6)
            dependent = table.cell_value(n, 7)
            data = table.cell_value(n, 8)
            expect = table.cell_value(n, 9)
            actual = table.cell_value(n, 10)
            result = table.cell_value(n, 11)
            setup = table.cell_value(n, 12)
            teardown = table.cell_value(n, 13)
            value = [case_model, case_number, case_title, path, is_token, method, dependent, data, expect, actual, result, setup, teardown]
            #logger.info(value)
            # 配合将每一行转换成元组存储，迎合 pytest的参数化操作，如不需要可以注释掉 value = tuple(value)
            value = tuple(value)
            data_list.append(value)
        return data_list, title_list

    def write_result(self, case_number, result):
        """

        :param case_number: 用例编号：case_001
        :param result: 需要写入的响应值
        :return:
        """
        row = int(case_number.split('_')[1])
        logger.info('开始回写实际响应结果到用例数据中.')
        result = json.dumps(result, ensure_ascii=False)
        new_excel = copy(self.book)
        ws = new_excel.get_sheet(0)
        # 9 是 实际响应结果栏在excel中的列数-1
        ws.write(row, 9, result)
        new_excel.save(self.excel_file)
        #logger.info(f'写入完毕:-写入文件: {self.excel_file}, 行号: {row + 1}, 列号: 9, 写入值: {result}')

    # 读实际的响应
    def read_actual(self, depend):
        """
        :param nrow: 列号
        :param depend: 依赖数据字典格式,前面用例编号，后面需要提取对应字段的jsonpath表达式
        {"case_001":["$.data.id",],}
        :return:
        """
        depend = json.loads(depend)
        # 用来存依赖数据的字典
        depend_dict = {}
        for k, v in depend.items():
            # 得到行号
            nrow = int(k.split('_')[1])
            table = self.book.sheet_by_index(0)
            # 得到对应行的响应,        # 9 是 实际响应结果栏在excel中的列数-1
            actual = json.loads(table.cell_value(nrow, 9))
            try:
                for i in v:
                    logger.info(f'i {i}, v {v}, actual {actual} \n {type(actual)}')
                    depend_dict[i.split('.')[-1]] = jsonpath.jsonpath(actual, i)[0]
            except TypeError as e:
                logger.error(f'实际响应结果中无法正常使用该表达式提取到任何内容，发现异常{e}')
        return depend_dict
